package com.zhss.demo.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorCrudDemo {

    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(
                1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(
                "localhost:2181",
                5000,
                3000,
                retryPolicy);
        client.start();

//        System.out.println("已经启动Curator客户端");
//
//        client.create()
//                .creatingParentsIfNeeded()
//                .withMode(CreateMode.PERSISTENT)
//                .forPath("/my/path", "100".getBytes());
//        byte[] dataBytes = client.getData().forPath("/my/path");
//        System.out.println(new String(dataBytes));
//
//        client.setData().forPath("/my/path", "110".getBytes());
//        dataBytes = client.getData().forPath("/my/path");
//        System.out.println(new String(dataBytes));
//
//        List<String> children = client.getChildren().forPath("/my");
//        System.out.println(children);
//
//        client.delete().forPath("/my/path");
//
//        Thread.sleep(Integer.MAX_VALUE);

        //获取监听对象
        NodeCache nodeCache = new NodeCache(client, "/leader");

            //添加监听
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            //监听回调函数，单个监听到节点发生增删改操作时会执行此方法
            @Override
            public void nodeChanged() throws Exception {
                String path = nodeCache.getCurrentData().getPath();
                System.out.println(path+"节点");

                //获取当前节点更新后的数据
                byte[] data = nodeCache.getCurrentData().getData();
                System.out.println("更新后的数据为：" + new String(data));
            }
        });

        //开启监听，如果为true则开启监听器
        nodeCache.start(true);

        System.out.println("监听器已开启！");
        //让线程休眠30s(为了方便测试)
        Thread.sleep(1000 * 60);
    }

}
